# -*- coding: utf-8 -*-

from collections import Iterable
from collections import Iterator
# 可迭代的对象：
# list、tuple 这些集合类
# 实现了 iterate 的的对象
#   字符串是实现了 Iterable
# 迭代器，有 yeild 的函数
# 实现了 next
isinstance("123",Iterable)

d = {'a': 1, 'b': 2, 'c': 3}

list = [1,2]

# 实现 next 方法的类实现了迭代器
# Iterator 是迭代器，主要实现了迭代的具体细节
# Iterable 是可迭代的对象，像 java 中的 iterable 的接口，在接口中的方法中要返回 迭代器对象

class myIterator(Iterator):

    i = 0
    def next(self):

        if i < 10 :
           return "myIterator"

        else:
            raise StopIteration


class myIterable(Iterable):

    def __iter__(self):
        return "ddddd";

i = myIterable()

print(isinstance(myIterator(),myIterator))

for x in myIterator():
    print(x)


print(isinstance(myIterator(),Iterator))
print(isinstance(i,Iterable))

#for a in myIterator():
#    print a


# class OwnIteror(Iterator):
#     def __init__(self, arrs):
#         self.index = 0
#         self.arrs = arrs
#
#     def next(self):
#         if self.index > len(self.arrs) - 1:
#             raise StopIteration
#         else:
#             self.index += 1
#             return self.arrs[self.index - 1]
#
#
# # 可迭代对象
# class OwnIterable(Iterable):
#     def __init__(self, arrs):
#         self.arrs = arrs
#
#     def __iter__(self):
#         return OwnIteror(self.arrs)
#
#
# for item in OwnIterable([1, 2, 3, 4, 4, 6]):
#     print item

# 列表生成式
# [ 表达式 迭代表达式 [条件表达式] ]

print map(lambda x:x*x , [ x for x in range(10) if x > 1] )
print [ x*x for x in range(10) ]


# 高价函数 map/reduce、filter、sorted

def f(x):
    return x == 1

print filter(f,[1,2,3])

def sort_methon(x,y):
    if x < y :
        return 1
    elif x > y :
        return -1
    return 0

print sorted([12,32,12,5,32],sort_methon)

# 装饰器，关键在于返回 wrapper 函数

# def log(f):
#     def wrapper(*args ,**kw):
#         print "execute ",f.__name__
#         f(*args ,**kw)
#
#     return  wrapper

def ff():
    print "I am a argurment function executed after target function"

def log(something,ff):
    def logger(f):
        def wapper(*args ,**kw):
            ff()
            print something,f.__name__
            f(*args ,**kw)

        return wapper

    return logger

@log("hello",ff)
def print_something():
    print "after print"

## 匿名函数的调用方式
func = print_something

func()